package com.haha.email;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

/**
 * description: java 获取url文件，并下载到本地
 * @version v1.0
 * @author w
 * @date 2019年7月30日 17:18:23
 **/

public class HttpFileTest {
	private static final String URL ="http://biz-report.100credit.cn/report/reportApi/downloadFileApi?id=627443d9f011a8459f14e7830ea1cddb";
	public static void main(String[] args) throws IOException {
		System.out.println("start ...");
		 URL url = new URL(URL);  
         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
         //设置超时间为3秒
         conn.setConnectTimeout(3*1000);
         // 获取文件大小
         int length = conn.getContentLength();
         System.out.println((length/1024)+" KB");
       
		// 解析获取文件名
		String headerField = conn.getHeaderField("Content-Disposition");
		String decode = URLDecoder.decode(headerField, "UTF-8");
		
		String fileName = decode.split(";")[1].split("=")[1].replaceAll("\"", "");
		System.out.println(fileName);
         
		InputStream inputStream = conn.getInputStream();
        OutputStream out = new FileOutputStream(new File("D:\\",fileName));
         
         int len ;
         byte[] buff = new byte[2048];
         while((len = inputStream.read(buff))!= -1) {
        	 out.write(buff, 0, len);
        	 out.flush();
         }
		 out.close();
		 inputStream.close();
		 System.out.println("over...");
	}
	
}
